package com.helloandroid

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Process
import android.view.*
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anythink.nativead.api.ATNativeAdView
import com.bumptech.glide.Glide
import com.helloandroid.activitys.*
import com.helloandroid.ads.SmallNativeAdUtil
import com.helloandroid.base.BaseFragment
import com.helloandroid.dialogs.BsTargetDialog
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.GUtils
import com.helloandroid.tools.MyLog
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.tencent.mm.opensdk.modelmsg.SendAuth
import kotlinx.coroutines.*

class WodeViewModel:ViewModel(){
    fun perSecondTick(action:()->Unit){
        viewModelScope.launch {
            launch(Dispatchers.Default){
                while (isActive){
                    delay(1000L)
                    withContext(Dispatchers.Main){
                        action()
                    }
                }
            }
        }
    }
}

class WodeFragment : BaseFragment() {

    lateinit var tvTarget: TextView
    lateinit var tvName: TextView
    lateinit var btnBindWx: Button
    lateinit var ivUserIcon: ImageView

    lateinit var tvCoin: TextView
    lateinit var tvMoney: TextView

    lateinit var bindWxReceiver: BroadcastReceiver

    lateinit var nativeView: ATNativeAdView

    val model:WodeViewModel by viewModels()

    // for test
    lateinit var llGM: View

    companion object {
        var gmTool: GMTool? = null
    }

    override fun getLayoutResId() = R.layout.fragment_wode

    override fun initView(view: View) {
        nativeView = findViewById(R.id.nativeView)
        tvTarget = findViewById(R.id.tvTarget)
        tvName = findViewById(R.id.tvName)
        ivUserIcon = findViewById(R.id.ivUserIcon)
        btnBindWx = findViewById(R.id.btnBindWx)
        tvCoin = findViewById(R.id.tvCoin)
        tvMoney = findViewById(R.id.tvMoney)
        llGM = findViewById(R.id.llGM)
        if (AppConfig.isGM) {
            llGM.visibility = View.VISIBLE
            findBtn(R.id.btnGM).setOnClickListener {
                reqGMWindow()
            }
            findBtn(R.id.btnKill).setOnClickListener {
                MyLog.info("杀死主进程....")
                Process.killProcess(Process.myPid())
            }
        } else {
            llGM.visibility = View.GONE
        }

        // 提现
        findViewById<Button>(R.id.btnTx).setOnClickListener {
            startActivity(Intent(activity, TXActivity::class.java))
        }

        // 步数记录
        findViewById<LinearLayout>(R.id.llBuShuRecord).setOnClickListener {
            startActivity(Intent(activity, BuShuRecordActivity::class.java))
        }

        // 身体报告
        findViewById<LinearLayout>(R.id.llBodyInfo).setOnClickListener {
            startActivity(Intent(activity, BodyInfoActivity::class.java))
        }

        // 步数小工具
        findViewById<LinearLayout>(R.id.llTools).setOnClickListener {
            startActivity(Intent(activity, BsToolActivity::class.java))
        }

        // 每日目标
        findViewById<LinearLayout>(R.id.llDailyTarget).setOnClickListener {
            activity?.apply {
                val dialog = BsTargetDialog(this)
                dialog.show()
            }
        }

        // 设置
        findViewById<LinearLayout>(R.id.llSetting).setOnClickListener {
            startActivity(Intent(activity, SettingActivity::class.java))
        }

        // 绑定微信
        findBtn(R.id.btnBindWx).setOnClickListener {
            bindWx()
        }

        updateUI()

        // 显示广告
        SmallNativeAdUtil.showNativeAd(requireActivity(), nativeView)
    }

    override fun initData() {
        bindWxReceiver = BindWxReceiver()
        requireActivity().registerReceiver(bindWxReceiver, IntentFilter(AppConfig.Action_User_BindWx))

        model.perSecondTick(this::perSecondTick)
    }

    private fun perSecondTick(){
        tvTarget.text = AppUtil.user.bs_target.toString()

        // 更新 金币或 money
        updateCoinAndMoney()
    }

    private fun bindWx() {
        if (!AppUtil.wxApi.isWXAppInstalled) {
            AppUtil.toast("您还未安装微信客户端!")
            return
        }
        val seq = SendAuth.Req()
        seq.scope = "snsapi_userinfo"
        seq.state = "ttjb_wx_login"
        AppUtil.wxApi.sendReq(seq)
    }

    override fun onDestroyView() {
        requireActivity().unregisterReceiver(bindWxReceiver)
        super.onDestroyView()
    }

    private fun updateCoinAndMoney() {
        val user = AppUtil.user
        tvCoin.text = "${user.coin}"
        tvMoney.text = "￥${GUtils.moneyToReadableString(user.money)}"
    }

    private fun reqGMWindow() {
        XXPermissions.with(this)
                .permission(Permission.SYSTEM_ALERT_WINDOW)
                .request { _, all ->
                    if (all) {
                        if (gmTool == null) {
                            gmTool = GMTool(requireActivity())
                        }
                        gmTool?.showWindow()
                    }
                }
    }


    inner class BindWxReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent != null && intent.action == AppConfig.Action_User_BindWx) {
                // 更新UI,更新玩家信息
                updateUI()
            }
        }
    }

    fun updateUI() {
        if (AppUtil.user.wx_id != "") {
            tvName.text = "${AppUtil.user.wx_name}"
            btnBindWx.visibility = View.GONE
            Glide.with(this)
                    .load(AppUtil.user.wx_icon)
                    .centerCrop()
                    .placeholder(R.drawable.dd_user_icon_default)
                    .into(ivUserIcon)

        } else {
            tvName.text = AppUtil.getWelComeName()
            btnBindWx.visibility = View.VISIBLE
            ivUserIcon.setImageResource(R.drawable.dd_user_icon_default)
        }

        // 更新当前金币信息
        updateCoinAndMoney()

        // 更新当前步数信息
        tvTarget.text = AppUtil.user.bs_target.toString()
    }
}